<template>
  <div class="profile">
    <div class="header">
      <div class="header_top">
        <img class="header_top_tx" src="@/assets/newui/home/basicAvatar.png" alt="">
        <div class="header_top_content">
          <div class="header_top_content_name ellipsis">{{ userInfo?.nickName }}</div>
          <div class="header_top_content_dandp flex-row">
            <div class="topbumen_l ellipsis flex-center">
              {{ userInfo.dept?.deptName }}
            </div>
            <div class="topbumen_r ellipsis flex-center">
              {{ positionName(userPost) }}
            </div>
          </div>
        </div>
        <img class="header_top_img" src="@/assets/newui/productList/icon_wodetu.png" alt="">
      </div>
      <div class="header_down">
        <div class="header_down_box">
          <div class="box_item">
            <div class="item_top"><span class="item_top_num">{{ jianlianNums }}</span>家</div>
            <div class="item_bottom">周建联商家</div>
          </div>
          <div class="box_item">
            <div class="item_top"><span class="item_top_num">{{ addProductNums }}</span>个</div>
            <div class="item_bottom">周新增商品</div>
          </div>
          <div class="box_item">
            <div class="item_top"><span class="item_top_num">{{ launchNums }}</span>个</div>
            <div class="item_bottom">周选品数</div>
          </div>
        </div>
      </div>
    </div>
    <div class="tabNav">
      <div class="tabNav_box">
        <div class="tabNav_box_item" v-if="userRoles.includes('recruit') || user.user.indexOf('superadmin') != -1"
          @click="routerToGo('/changeHands')">
          <img class="item_img" src="@/assets/newui/productList/icon_shangpinyizhu.png" alt="">
          <div class="item_text">商品易主</div>
        </div>
        <div class="tabNav_box_item" @click="weChatSet">
          <img class="item_img" src="@/assets/newui/productList/icon_yaoqingruzhu.png" alt="">
          <div class="item_text">邀请入驻</div>
        </div>
        <div class="tabNav_box_item" @click="routerToGo('/productSelection')">
          <img class="item_img" src="@/assets/newui/productList/icon_shenpishuju.png" alt="">
          <div class="item_text">审批数据</div>
        </div>
      </div>
      <van-popup v-model:show="showQRcode" style="background-color: revert;">
        <div class="QRcode">
          <div class="code_title">
            <span>【{{ userInfo?.nickName }}】邀请您扫码入驻</span><br>
            <span>惠麦供应链系统</span>
            <van-image class="guanbi_cion" :src="guanbiIcon" @click="showQRcode = false" />
          </div>
          <div class="code">
            <vue-qr class="code_content" ref="qrcode" :text="qrCodeValue" :size="500"></vue-qr>
          </div>
          <div class="QR_BT_box">

            <van-image class="weixin_cion" :src="weixinIcon" @click="shareToWechat" />
            <van-image class="weixin_cion" :src="downloadIcon" @click="download" v-throttle:click />
          </div>
        </div>
      </van-popup>
    </div>
    <div class="personage">
      <div class="personage_box">
        <div class="box_title">我的卡片</div>
        <div class="box_item" v-for="item in personageList" :key="item.id" @click="routerToGo(item.url, item.query)">
          <img class="box_item_left" :src="item.imgUrl" alt="">
          <div class="box_item_text">{{ item.text }}</div>
          <div class="box_item_right">
            <span v-if="item.text === '消息中心' && messageTotal">{{ messageTotal }}</span>
            <img class="right_img" src="@/assets/operation/icon_huisejiantou.png" alt="">
          </div>
          <!-- <img class="box_item_right" src="@/assets/operation/icon_huisejiantou.png" alt=""> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useRouter } from 'vue-router'
import { userStore } from "@/store/user";
import { loginStore } from "@/store/login";
import { getEnvValue } from "@/utils/index";
import { getInfo } from "@/api/supplierList/index";
import dayjs from 'dayjs'
import { totalByUserIdAndTime } from "@/api/productList/index";
import { storeToRefs } from "pinia";
import { queryDeptCount } from '@/api/operation/index'
import vueQr from 'vue-qr/src/packages/vue-qr.vue';
import { showToast } from "vant";

const guanbiIcon = new URL(
  "@/assets/newui/home/icon_guanbi@2x.png",
  import.meta.url
).href;
const weixinIcon = new URL(
  "@/assets/newui/home/icon_weixin@2x.png",
  import.meta.url
).href;
const downloadIcon = new URL(
  "@/assets/newui/home/icon_baocunbendi@2x.png",
  import.meta.url
).href;
const icon_xiaoxizhongxin = new URL(
  "@/assets/operation/icon_xiaoxizhongxin.png",
  import.meta.url
).href;
const icon_gerenzhongxin = new URL(
  "@/assets/operation/icon_gerenzhongxin.png",
  import.meta.url
).href;
const icon_jianyiyufankui = new URL(
  "@/assets/operation/icon_jianyiyufankui.png",
  import.meta.url
).href;
const icon_shezhi = new URL(
  "@/assets/operation/icon_shezhi.png",
  import.meta.url
).href;

const router = useRouter()

const user = userStore();
const userRoles = user.user.join(',')
const store = loginStore();
const { token } = storeToRefs(store);

const userInfo = ref<any>({});
const userPost = ref<any>([]);

const addProductNums = ref(0);
const jianlianNums = ref(0);
const launchNums = ref(0);

const showQRcode = ref(false)
const qrCodeValue = ref('');
const qrcode = ref();
// 消息数量
const messageTotal = ref()

const personageList = ref([
  { text: '消息中心', id: 1, url: '/notice', query: { type: '招商部' }, imgUrl: icon_xiaoxizhongxin },
  { text: '个人信息', id: 2, url: '/profile', query: null, imgUrl: icon_gerenzhongxin },
  { text: '建议与反馈', id: 3, url: '/feedback', query: null, imgUrl: icon_jianyiyufankui },
  { text: '设置', id: 4, url: '/setIndex', query: null, imgUrl: icon_shezhi },
])

const getCountNotReadMsg = async () => {
  // 获取消息数量
  const { data } = await queryDeptCount({})
  messageTotal.value = Number(data?.readCount) + Number(data?.waitCount)
}
getCountNotReadMsg()

const getList = async () => {
  const res = await getInfo();
  userInfo.value = res.data.user;
  userPost.value = res.data.posts || []
};
// 反显职位权限名称
const positionName = (data: any) => {
  let name: any = []
  data.forEach((item: any) => {
    name.push(item.postName)
  })
  return name.join('/')
}

/** 获取首页数据简报 */
const gettotalByUserIdAndTime = async () => {
  const res = await totalByUserIdAndTime({
    startTime: dayjs().subtract(6, 'day').format('YYYY-MM-DD') + ' 00:00:00',
    endTime: dayjs().format('YYYY-MM-DD') + ' 23:59:59'
  })
  res.data.forEach(item => {
    if (item.auditStatus == '增品') {
      addProductNums.value = item.total
    } else if (item.auditStatus == '建联') {
      jianlianNums.value = item.total
    } else if (item.auditStatus == '选中') {
      launchNums.value = item.total
    }
  })
}

// 路由跳转
const routerToGo = (url: string, query?: any) => {
  if (query) {
    router.push({
      path: url,
      query: query
    })
  } else {
    router.push(url);
  }
}
// 邀请入驻
const weChatSet = () => {
  // 邀请入驻招商员权限
  if (userInfo.value.roles && userRoles.includes('recruitStaff')) {
    if (getEnvValue("VITE_APP_NEED_HEAD") == '灰度') {
      // 当前灰度环境暂无小程序，先放开发
      qrCodeValue.value = `https://supply-pc-pre.huimaisoft.com:19203?deptName=${userInfo.value.dept?.deptName}&deptId=${userInfo.value.dept?.deptId}&roleName=${userInfo.value.userName}&type=app`
    } else if (getEnvValue("VITE_APP_NEED_HEAD") == '测试' || getEnvValue("VITE_APP_NEED_HEAD") == '开发') {
      qrCodeValue.value = `https://dev-supply.huimaisoft.com:19315?deptName=${userInfo.value.dept?.deptName}&deptId=${userInfo.value.dept?.deptId}&roleName=${userInfo.value.userName}&type=app`
    } else {
      qrCodeValue.value = `https://store.huimaisoft.com:19102?deptName=${userInfo.value.dept?.deptName}&deptId=${userInfo.value.dept?.deptId}&roleName=${userInfo.value.userName}&type=app`
    }
    showQRcode.value = true
  } else {
    showToast('暂无邀请入驻权限')
  }
}
// 分享
const shareToWechat = () => {
  // 获取二维码 base64 数据

  let imgurl = qrcode.value.imgUrl; // qrcode.value.imgUrl 是包含 base64 数据的完整 URL

  // 提取 base64 数据部分
  if (imgurl.includes(";base64,")) {
    imgurl = imgurl.split(";base64,")[1]; // 获取 base64 数据部分

  } else {
    // 如果 URL 不包含 ";base64,"，可能需要根据具体情况进行处理
    console.error('URL中不包含";base64,"，请确认URL格式是否正确。');
  }

  // 发送分享请求给webview
  (window as any).uni.webView.postMessage({
    data: {
      type: "img",
      url: imgurl,
      // 方式：分享
      function: "share",
      header: {
        Authorization: `Bearer ${token.value}`,
        clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
      },
    },
  });
}
// 下载
const download = () => {
  // // TODO 接口返回数据  
  // let res = "https://dev-supply.huimaisoft.com:19315"
  // // 数据返回生产二维码
  // qrCodeValue.value = res;

  // 生成二维码是属于异步行为，所以下载二维码也为异步行为

  const timer = setTimeout(() => {

    let imgurl = qrcode.value.imgUrl; //  qrcode.value.imgUrl 是包含 base64 数据的完整 URL

    // 提取 base64 数据部分
    if (imgurl.includes(";base64,")) {
      imgurl = imgurl.split(";base64,")[1]; // 获取 base64 数据部分

    } else {
      // 如果 URL 不包含 ";base64,"，可能需要根据具体情况进行处理
      console.error('URL中不包含";base64,"，请确认URL格式是否正确。');
    }

    // 发送图片请求给webview
    (window as any).uni.webView.postMessage({
      data: {
        type: "img",
        url: imgurl,
        // 方式：保存
        function: "save",
        header: {
          Authorization: `Bearer ${token.value}`,
          clientid: "e5cd7e4891bf95d1d19206ce24a7b32e",
        },
      },
    });
    clearTimeout(timer);
  });
}

onMounted(() => {
  getList();
  gettotalByUserIdAndTime()
})


</script>

<style lang="less" scoped>
.profile {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-flow: column;
  background: #F6FAFF;
  background-image: url('../../assets/newui/productList/icon_shangpinbeijing@2x.png');
  background-size: 100% 190px;
  background-repeat: no-repeat;
  padding-top: 44px;
  box-sizing: border-box;

  .header {
    width: 100%;

    .header_top {
      display: flex;

      .header_top_tx {
        width: 66px;
        height: 66px;
        margin: 12px 0 0 12px;
        border-radius: 50%;
      }

      .header_top_content {
        flex: 1;
        min-width: 0;
        margin-top: 22px;

        .header_top_content_name {
          font-family: PingFangSC, PingFang SC;
          font-weight: 600;
          font-size: 16px;
          line-height: 16px;
          color: #1A1B1C;
          text-align: left;
          font-style: normal;
          max-width: 200px;
          margin-left: 7px;
        }

        .header_top_content_dandp {
          margin-top: 10px;
          font-family: PingFangSC, PingFang SC;
          font-weight: 500;
          font-size: 14px;
          margin-left: 3px;


          .topbumen_l {
            height: 22px;
            width: 108px;
            line-height: 22px;
            color: #1881FF;
            position: relative;
            background: url("@/assets/newui/home/icon_bumen@2x.png");
            background-size: 100% 100%;
            background-repeat: no-repeat;

          }

          .topbumen_r {
            font-family: FontName;
            height: 22px;
            width: 92px;
            line-height: 22px;
            color: #FFFFFF;
            position: relative;
            background: url("@/assets/newui/home/icon_mingcheng@2x.png");
            background-size: 100% 100%;
            background-repeat: no-repeat;
            margin-left: -6px;

          }
        }
      }

      .header_top_img {
        width: 60px;
        height: 60px;
        margin: 32px 32px 0 10px;
      }
    }

    .header_down {
      width: 100%;
      padding: 0 15px;
      box-sizing: border-box;
      margin-top: 3px;
      margin-bottom: 10px;

      .header_down_box {
        width: 100%;
        height: 76px;
        background-image: url('../../assets/newui/productList/icon_lanzisebeijing.png');
        background-size: 100% 100%;
        background-repeat: no-repeat;
        display: flex;
        align-items: center;
        justify-content: space-around;

        .box_item {
          flex: 1;
          min-width: 0;
          display: flex;
          flex-flow: column;
          align-items: center;
          justify-content: center;
          font-weight: 400;
          font-size: 12px;
          color: #FFFFFF;

          .item_top {
            .item_top_num {
              font-weight: 600;
              font-size: 20px;
            }
          }

          .item_bottom {
            margin-top: 5px;
          }
        }
      }
    }


  }

  .tabNav {
    width: 100%;
    padding: 0 15px;
    box-sizing: border-box;

    .tabNav_box {
      width: 100%;
      height: 95px;
      background: #FFFFFF;
      border-radius: 5px;
      display: flex;
      align-items: center;

      .tabNav_box_item {
        flex: 1;
        min-width: 0;
        display: flex;
        flex-flow: column;
        align-items: center;
        justify-content: center;

        .item_img {
          width: 28px;
          height: 28px;
          margin-bottom: 10px;
        }

        .item_text {
          font-weight: 400;
          font-size: 14px;
          color: #1A1B1C;
        }
      }
    }

    .QRcode {
      width: 315px;
      height: 370px;
      background-color: white;
      border-radius: 5px;

      .code_title {
        text-align: center;
        font-size: 16px;
        font-weight: 500;
        padding-top: 28px;
        line-height: 22px;
        color: #1A1B1C;

        .guanbi_cion {
          width: 14px;
          height: 14px;
          position: absolute;
          top: 15px;
          right: 15px;
        }
      }

      .code {
        width: 201px;
        height: 201px;
        margin: 15px 57px;
        box-sizing: border-box;
        padding: 20px;
        background: #F6FAFF;
        border-radius: 10px;

        .code_content {
          width: 100%;
          height: 100%;
        }
      }

      .QR_BT_box {
        width: 201px;
        box-sizing: border-box;
        margin: 0 auto;
        margin-top: 20px;
        padding: 0 30px;
        display: flex;
        justify-content: space-between;

        .weixin_cion {
          width: 40px;
          height: 40px;
        }
      }

    }
  }

  .personage {
    margin-top: 10px;
    flex: 1;
    min-height: 0;
    width: 100%;
    padding: 0 15px;
    box-sizing: border-box;
    overflow-y: auto;

    .personage_box {
      width: 100%;
      background: #FFFFFF;
      border-radius: 5px;
      padding: 15px 15px 0;
      box-sizing: border-box;
      display: flex;
      flex-flow: column;

      .box_title {
        font-weight: 500;
        font-size: 16px;
        color: #1A1B1C;
        margin-bottom: 28px;
      }

      .box_item {
        width: 100%;
        display: flex;
        align-items: center;
        margin-bottom: 28px;

        .box_item_left {
          width: 20px;
          height: 20px;
          margin-right: 13px;
        }

        .box_item_text {
          flex: 1;
          min-width: 0;
          font-weight: 400;
          font-size: 16px;
          color: #1A1B1C;
        }

        .box_item_right {
          display: flex;
          align-items: center;

          span {
            width: 28px;
            height: 20px;
            line-height: 20px;
            text-align: center;
            background: #FC2540;
            border-radius: 10px;
            margin-right: 15px;
            font-weight: 400;
            font-size: 14px;
            color: #FFFFFF;
          }

          .right_img {
            width: 7px;
            height: 12px;
          }
        }
      }
    }
  }
}
</style>
